<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/8 0008
 * Time: 15:58
 */

namespace Admin\Model;

use Think\Image;
use Think\Model;
use Think\Page;
use Think\Upload;

class GoodsModel extends Model
{
    // 添加时调用create方法允许介接受的字段
    protected $insertFields = 'goods_name,market_price,shop_price,is_on_sale,goods_desc,brand_id';

    protected $updateFields = 'id,goods_name,market_price,shop_price,is_on_sale,goods_desc,brand_id';
    //定义规则
    protected $_validate = array(
        array('goods_name', 'require', '商品名称不能为空', 1),
        array('market_price', 'currency', '市场价格必须是货币类型!', 1),
        array('shop_price', 'currency', '本店价格必须是货币类型', 1),
    );

    protected function _before_insert(&$data, $option)
    {
        /**************** 处理LOGO *******************/
        // 判断有没有选择图片
        if ($_FILES['logo']['error'] == 0) {
            $ret = uploadOne('logo', 'Goods', array(
                array(700, 700),
                array(350, 350),
                array(130, 130),
                array(50, 50),
            ));
            $data['logo'] = $ret['images'][0];
            $data['mbig_logo'] = $ret['images'][1];
            $data['big_logo'] = $ret['images'][2];
            $data['mid_logo'] = $ret['images'][3];
            $data['sm_logo'] = $ret['images'][4];
        }
//        插入前先设置好时间
        $data['addtime'] = date('Y-m-d,H-i-s', time());
        //用htmlpurifier过滤
        $data['goods_desc'] = removeXSS($_POST['goods_desc']);

//        //处理logo
//        //获取logo,判断logo大小格式
//        if ($_FILES['logo']['error'] == 0) {
//            $config = array(
//                'maxSize' => 1024 * 1024,
//                'exts' => array('jpg', 'gif', 'png', 'jpeg'),
//                'rootPath' => './Public/Uploads/',
//                'savePath' => 'Goods/'
//
//            );
//            $upload = new Upload($config);
//            $info = $upload->upload();
//            if (!$info) {
//                $this->error = $upload->getError();
//                return FALSE;
//            } else {
//                //存储logo,生成缩略图
//                $logo = $info['logo']['savepath'] . $info['logo']['savename'];
////               拼接缩略图的路径
//                $mbiglogo = $info['logo']['savepath'] . 'mbig_' . $info['logo']['savename'];
//                $biglogo = $info['logo']['savepath'] . 'big_' . $info['logo']['savename'];
//                $midlogo = $info['logo']['savepath'] . 'mid_' . $info['logo']['savename'];
//                $smlogo = $info['logo']['savepath'] . 'sm_' . $info['logo']['savename'];
//                $image = new Image();
//                $image->open('./Public/Uploads/' . $logo);
//                $image->thumb(700, 700)->save('./Public/Uploads/' . $mbiglogo);
//                $image->thumb(350, 350)->save('./Public/Uploads/' . $biglogo);
//                $image->thumb(130, 130)->save('./Public/Uploads/' . $midlogo);
//                $image->thumb(50, 50)->save('./Public/Uploads/' . $smlogo);
//                $data['logo'] = $logo;
//                $data['mbig_logo'] = $mbiglogo;
//                $data['big_logo'] = $biglogo;
//                $data['mid_logo'] = $midlogo;
//                $data['sm_logo'] = $smlogo;
//                //插入前先设置好时间
//                $data['addtime'] = date('Y-m-d,H-i-s', time());
//                //用htmlpurifier过滤
//                $data['goods_desc'] = removeXSS($_POST['goods_desc']);
//            }
//
//        }

    }

    /**
     *实现翻页,排序,搜索
     */
    public function search($perPage = 15)
    {


        //搜索
        $where = array();
        //品牌id
        $brandId = I('get.brand_id');
        if ($brandId) {
//            $where['a.brand_id'] = array('eq',$brandId);
            $where['a.brand_id'] = $brandId;
        }
        $gn = I('get.gn');
        //商品名称
        if ($gn) {
            $where['a.goods_name'] = array('like', "%$gn%");
        }
        //价格
        $fp = I('get.fp');
        $tp = I('get.tp');
        if ($fp && $tp) {
            $where['a.shop_price'] = array('between', array($fp, $tp));
        } elseif ($fp) {
            $where['a.shop_price'] = array('egt', $fp);
        } elseif ($tp) {
            $where['a.shop_price'] = array('elt', $tp);
        }
        //是否上架
        $ios = I('get.ios');
        if ($ios) {
            $where['a.is_on_sale'] = array('eq', $ios);
        }
        //添加时间
        $fa = I('get.fa');
        $ta = I('get.ta');
        if ($fa && $ta) {
            $where['a.addtime'] = array('between', array($fa, $ta));
        } elseif ($fa) {
            $where['a.addtime'] = array('egt', $fa);
        } elseif ($ta) {
            $where['a.addtime'] = array('elt', $ta);
        }
        /*******************排序**************************/
        $orderby = 'a.id';
        $orderway = 'desc';
        $odby = I('get.odby');
        if ($odby) {
            if ($odby == 'id_asc') {
                $orderby = 'a.id';
                $orderway = 'asc';
            } elseif ($odby == 'price_desc') {
                $orderby = 'a.shop_price';
                $orderway = 'desc';
            } elseif ($odby == 'price_asc') {
                $orderby = 'a.shop_price';
                $orderway = 'asc';
            } elseif ($odby == 'id_desc') {
                $orderby = 'a.id';
                $orderway = 'desc';
            }
        }
        //取出总记录数
        $count = $this->alias('a')->where($where)->count();
//       生成翻页对象
        $pageObj = new Page($count, $perPage);
        $pageObj->setConfig('next', '下一页');
        $pageObj->setConfig('prev', '上一页');
        //生成页面下面显示的上一页,下一页的字符串
        $pagerString = $pageObj->show();
        /**************取某一页数据******************/
        $data = $this->order("$orderby $orderway")
            ->field('a.*,b.brand_name')
            ->alias('a')
            ->join('LEFT JOIN __BRAND__ b ON a.brand_id = b.id')
            ->where($where)
            ->limit($pageObj->firstRow . "," . $pageObj->listRows)
            ->select();
//        var_dump( $this->getLastSql());
        //返回数据
        return array(
            'data' => $data,
            'page' => $pagerString,
        );
    }

    public function _before_update(&$data, $option)
    {

        $id = $option['where']['id'];
        /**处理相册图片**/
        if (isset($_FILES['pic'])) {
            $pics = array();
            foreach ($_FILES['pic']['name'] as $k => $v) {
                $pics[] = array(
                    'name' => $v,
                    'type' => $_FILES['pic']['type'][$k],
                    'tmp_name' => $_FILES['pic']['tmp_name'][$k],
                    'error' => $_FILES['pic']['error'][$k],
                    'size' => $_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel=D('goods_pic');
            foreach ($pics as $k => $v) {
                if ($v['error'] == 0) {
                    $ret = uploadOne($k, 'Goods', array(
                        array(650,650),
                        array(350,350),
                        array(50,50),

                    ));
                    if ($ret['ok'] == 1) {
//                        $oldpic=$gpModel->where("goods_id=$id")->field('pic,sm_pic,big_pic,mid_pic')->find();
//                        deleteImage($oldpic);
                        $gpModel->add(array(
                            'pic' => $ret['images'][0],
                            'big_pic' => $ret['images'][1],
                            'mid_pic' => $ret['images'][2],
                            'sm_pic' => $ret['images'][3],
                            'goods_id' => $id,

                        ));
                    }
                }
            }
        }
        /*************************处理会员价格*******************************/
        $mp = I('post.member_price');
        $mpModel = D('member_price');
        $mpModel->where(array('goods_id' => array('eq', $id)))->delete();
        foreach ($mp as $k=>$v) {
            $_v = (float)$v;
            if ($_v > 0) {
                $mpModel->add(array(
                    'price' => $_v,
                    'level_id' => $k,
                    'goods_id' => $id
                ));
            }
        }
        // 判断有没有选择图片
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
            $oldlogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find();
            deleteImage($oldlogo);
            $ret = uploadOne('logo', 'Goods', array(
                array(700, 700),
                array(350, 350),
                array(130, 130),
                array(50, 50),
            ));
            var_dump($ret);
            $data['logo'] = $ret['images'][0];
            $data['mbig_logo'] = $ret['images'][1];
            $data['big_logo'] = $ret['images'][2];
            $data['mid_logo'] = $ret['images'][3];
            $data['sm_logo'] = $ret['images'][4];
        }
//        插入前先设置好时间
        $data['addtime'] = date('Y-m-d,H-i-s', time());
        //用htmlpurifier过滤
        $data['goods_desc'] = removeXSS($_POST['goods_desc']);



    }

    public function _after_insert($data, $option)
    {
        $mldata = I('post.member_price');
        $mlmoudle = D("member_price");
        foreach ($mldata as $k => $v) {

            $_v = intval($v);
            if ($_v > 0) {
                $mlmoudle->add(array(
                    'level_id' => $k,
                    'price' => $v,
                    'goods_id' => $data['id'],
                ));
            }
        }

        $id = $data['id'];
        /**处理相册图片**/
        if (isset($_FILES['pic'])) {
            $pics = array();
            foreach ($_FILES['pic']['name'] as $k => $v) {
                $pics[] = array(
                    'name' => $v,
                    'type' => $_FILES['pic']['type'][$k],
                    'tmp_name' => $_FILES['pic']['tmp_name'][$k],
                    'error' => $_FILES['pic']['error'][$k],
                    'size' => $_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel=D('goods_pic');
            foreach ($pics as $k => $v) {
                if ($v['error'] == 0) {
                    $ret = uploadOne($k, 'Goods', array(
                        array(650,650),
                        array(350,350),
                        array(50,50),

                    ));
                    if ($ret['ok'] == 1) {
//                        $oldpic=$gpModel->where("goods_id=$id")->field('pic,sm_pic,big_pic,mid_pic')->find();
//                        deleteImage($oldpic);
                        $gpModel->add(array(
                            'pic' => $ret['images'][0],
                            'big_pic' => $ret['images'][1],
                            'mid_pic' => $ret['images'][2],
                            'sm_pic' => $ret['images'][3],
                            'goods_id' => $id,

                        ));
                    }
                }
            }
        }
    }

    public function _before_delete($option)
    {
        $id = $option['where']['id'];
        $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
        deleteImage($oldLogo);
        $mpModel = D('member_price');
        $mpModel->where("goods_id=$id")->delete();
    }
}